package com.charles.seckillsystem.controller;

import com.charles.seckillapi.domain.SysUser;
import com.charles.seckillapi.model.UserLogin;
import com.charles.seckillcommon.core.domain.AjaxResult;
import com.charles.seckillcommon.core.domain.R;
import com.charles.seckillcommon.core.exceptions.ServiceException;
import com.charles.seckillcommon.core.utils.BcryptUtil;
import com.charles.seckillcommon.security.utils.ThreadUtil;
import com.charles.seckillsystem.mapper.SysUserMapper;
import com.charles.seckillsystem.vo.LoginInfo;
import com.charles.seckillsystem.vo.ModifyPasswordForm;
import com.charles.seckillsystem.vo.SearchUserForm;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
public class SysUserController {
    
    @Resource
    private SysUserMapper sysUserMapper;
    
    /**
     * 通过身份证号码获取客户
     */
    @GetMapping("/info/{user_card}")
    public R<UserLogin> userInfo(@PathVariable("user_card") String user_card) {
        SysUser sysUser = sysUserMapper.queryUserByUserCard(user_card);
        if (sysUser == null) {
            return R.fail("身份证号码或密码错误");
        }
        UserLogin userLogin = new UserLogin();
        userLogin.setSysUser(sysUser);
        return R.success(userLogin);
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    public R<Boolean> register(@RequestBody SysUser sysUser) {
        return sysUserMapper.addUser(sysUser) ? R.success() : R.fail();
    }

    /**
     * 获取登录用户
     */
    @GetMapping("getUser")
    public AjaxResult getUser() {
        String userId = ThreadUtil.getUserId();
        LoginInfo user = sysUserMapper.queryLoginInfoById(Long.parseLong(userId));
        return AjaxResult.success(user);
    }

    /**
     * 通过客户姓名和身份证号码查询客户
     */
    @PostMapping("searchUser")
    public AjaxResult searchUser(@RequestBody SearchUserForm searchUserForm) {
        SysUser sysUser = sysUserMapper.queryUserByUserCard(searchUserForm.getUserCard());
        
        if (sysUser == null) {
            throw new ServiceException("客户信息不存在");
        }
        
        if (!sysUser.getUser_name().equals(searchUserForm.getUsername())) {
            throw new ServiceException("客户信息不匹配");
        }
        
        return AjaxResult.success();
    }

    /**
     * 修改客户密码
     */
    @PutMapping("modifyPassword")
    public AjaxResult modifyPassword(@RequestBody ModifyPasswordForm form) {
        
        if (form.getPassword().length() < 6 || form.getPassword().length() > 10) {
            return AjaxResult.error("密码格式不规范");
        }
        
        form.setPassword(BcryptUtil.hashPassword(form.getPassword()));
        sysUserMapper.modifyPassword(form);
        return AjaxResult.success();
    }
}
